<template>
  <Drawer
    id="produceTaskWrapper"
    placement="left"
    v-model="showPopup"
    :closable="false"
    :mask="false"
    :mask-closable="false"
    :transfer="false"
    :inner="true"
  >
    <Form class="produceTask" :label-width="80">
      <p class="formTitle">参数设置</p>
      <FormItem :model="formItem" label="流程选择">
        <Select v-model="formItem.taskName">
          <Option
            v-for="item in flowList"
            :value="item.flowName"
            :key="item.flowId"
            transfer
            >{{ item.flowName }}</Option
          >
        </Select>
      </FormItem>
     
      <FormItem v-show= "isUserCommonImage()" 
        :model="formItem" 
        :label="nameShow()">
        <div v-if="isInputIamgePath()" style="display: flex">
          <!-- 正射产品   共享目录选择-->
          <Input v-model="formItem.imgDir" :title="formItem.imgDir" />
          <CButton
            @click="selectServerFile"
            color="info"
            class="system-btn-style rightBtn"
            >...</CButton
          >
        </div>
        <div v-else style="display: flex">
          <Input v-model="formItem.imgDir" :title="formItem.imgDir" disabled />
          <!--左侧树筛选目录选择  -->
          <CButton
            @click="treeDataFile('imgDir')"
            color="info"
            class="system-btn-style rightBtn">...</CButton>
        </div>
      </FormItem>
      <!-- 当前灾害范围 -->
      <FormItem v-show="this.productionTag === 'YJHLDQFWJCCP'" :model="formItem" label="灾前水体">
        <div style="display: flex">
          <Input v-model="formItem.waterFileFront" :title="formItem.waterFileFront" disabled />
          <CButton
            @click="treeDataFile('imgZQST')"
            color="info"
            class="system-btn-style rightBtn"
            >...</CButton>
        </div>
      </FormItem>
      <FormItem v-show="this.productionTag === 'YJHLDQFWJCCP'" :model="formItem" label ="灾中水体">
        <div style="display: flex">
          <Input v-model="formItem.waterFile" :title="formItem.waterFile" disabled />
            <CButton
              @click="treeDataFile('imgZZST')"
              color="info"
              class="system-btn-style rightBtn"
              >...</CButton>
        </div>
      </FormItem>

      <!-- 火烧迹地变化 -->
      <FormItem v-show="this.productionTag === 'YJHSJDBHTQCP'" :model="formItem" label="前景影像">
        <div style="display: flex">
          <Input v-model="formItem.foregroundImage" :title="formItem.foregroundImage" disabled />
          <CButton
            @click="treeDataFile('imgFont')"
            color="info"
            class="system-btn-style rightBtn"
            >...</CButton>
        </div>
      </FormItem>
      <FormItem v-show="this.productionTag === 'YJHSJDBHTQCP'" :model="formItem" label ="后景影像">
        <div style="display: flex">
          <Input v-model="formItem.backgroundImage" :title="formItem.backgroundImage" disabled />
            <CButton
              @click="treeDataFile('imgBack')"
              color="info"
              class="system-btn-style rightBtn"
              >...</CButton>
        </div>
      </FormItem>
      <!-- 灾前NDVI -->
      <FormItem v-show="isUserFrontNDVI()" :model="formItem" label="灾前NDVI">
          <div style="display: flex">
            <Input v-model="formItem.frontNDVI" :title="formItem.frontNDVI" disabled />
            <CButton
              @click="treeDataFile('FrontNDVI')"
              color="info"
              class="system-btn-style rightBtn"
              >...</CButton>
          </div>
      </FormItem>
      <!-- 灾后NDVI -->
      <FormItem v-show="isUserAfterNDVI()" :model="formItem" label="灾后NDVI">
          <div style="display: flex">
            <Input v-model="formItem.afterNDVI" :title="formItem.afterNDVI" disabled />
            <CButton
              @click="treeDataFile('AfterNDVI')"
              color="info"
              class="system-btn-style rightBtn"
              >...</CButton>
          </div>
      </FormItem>

      <FormItem
        v-show="isUserRegion()"
        :model="formItem"
        label="区域选择"
        style="margin-left: -9px"
      >
        <Select
          v-model="regionSelected"
          @on-change="regionSelectedChange"
        >
          <Option
            v-for="item in regionResultIDListX"
            :value="item.regionID"
            :key="item.regionID"
          >
            {{ item.regionName }}
          </Option>
        </Select>
      </FormItem>

      <FormItem
        v-show="isUserDate()"
        :model="formItem"
        label="数据日期:"
        style="margin-left: -9px"
      >
      <Input v-model="formItem.dataDate" :title="formItem.dataDate" placeholder="日期格式示例: 20220629"/>
      </FormItem>

      <RadioGroup
        v-show="productionTag === 'YJCJCP'"
        v-model="radioGroupRengion"
        vertical
        class="radioGroup"
      >
        <div style="display: flex; height: 34px; margin-right: 8px">
          <Radio label="region"> <span></span></Radio>
          <FormItem
            :model="formItem"
            label="区域选择"
            style="margin-left: -9px"
          >
            <Select
              v-model="regionSelected"
              @on-change="regionSelectedChange"
              :disabled="radioGroupRengion === 'region' ? false : true"
            >
              <Option
                v-for="item in regionResultIDListX"
                :value="item.regionID"
                :key="item.regionID"
              >
                {{ item.regionName }}
              </Option>
            </Select>
          </FormItem>
        </div>

        <Radio label="shpFile" style="display: flex; margin-top: 32px">
          <FormItem :model="formItem" label="shp文件">
            <div style="display: flex">
              <Input
                v-model="formItem.shpFile"
                :title="formItem.shpFile"
                :disabled="radioGroupRengion === 'shpFile' ? false : true"
              />
              <CButton
                @click="selectServerShpFile"
                color="info"
                class="system-btn-style"
                style="
                  width: 45px;
                  height: 34px;
                  margin-left: 10px;
                  margin-top: -2px;"
                :disabled="radioGroupRengion === 'shpFile' ? false : true"
                >...</CButton
              >
            </div>
          </FormItem>
        </Radio>
      </RadioGroup>

      <FormItem class="formBtnGroup">
        <Button @click="formSubmit" type="primary">提交</Button>
        <Button @click="formCancel" style="margin-left: 8px">取消</Button>
      </FormItem>
    </Form>
    <FileCatalog
      ref="refFileCatalogModal"
      v-if="fileCatalogModal"
      :modalShow="fileCatalogModal"
      @closed="fileCatalogModalClose"
      @menuOk="fileCatalogModalOk"
    ></FileCatalog>
  </Drawer>
</template>
<script>
import Axios from "axios";
import FileCatalog from "../jobProcess/fileCatalog.vue";
export default {
  name: "produceTask",
  components: {
    FileCatalog,
  },
  props: {
    showPopup: {
      type: Boolean,
      default: false,
    },
    treeShow: {
      type: Boolean,
      default: false,
    },

    imgDir: {
      type: Array,
    },
    waterFileFront: {
      type: Array,
    },
    waterFile: {
      type: Array,
    },
    foregroundImage: {
      type: Array,
    },
    backgroundImage: {
      type: Array,
    },
    frontNDVI: {
      type: Array,
    },
    afterNDVI: {
      type: Array,
    },
    dataPartValue: {
      type: Boolean,
    }
  },
  data() {
    return {
      radioGroupRengion: "region",
      isRegionRadio: true, //该值和变量radioGroupRengion绑定，region就为true
      isSelectShp: false,
      regionSelected: "",

      regionResultIDListX: [],
      taskAreaList: [],
      productionName: "",
      productionTag: "",
      fileCatalogModal: false,
      flowList: [],
      formItem: {
        taskName: "",
        imgDir: [],
        areas: [],
        shpFile: "",
        dataDate:"",
        waterFileFront:"",
        waterFile: "",
        foregroundImage: "",
        backgroundImage: "",
        frontNDVI:"",
        afterNDVI:"",
      },
      regionCode: 0,
      flowId: -1,
      taskSource: -1,
      taskId: -1,
      merge: false,
    };
  },
  watch: {
    imgDir: {
      handler(val) {
        this.formItem.imgDir = val;
      },
      deep: true,
      immediate: true,
    },
    waterFileFront: {
      handler(val) {
        this.formItem.waterFileFront = val;
      },
      deep: true,
      immediate: true,
    },
    waterFile: {
      handler(val) {
        this.formItem.waterFile = val;
      },
      deep: true,
      immediate: true,
    },
    foregroundImage: {
      handler(val) {
        this.formItem.foregroundImage = val;
      },
      deep: true,
      immediate: true,
    },
    backgroundImage: {
      handler(val) {
        this.formItem.backgroundImage = val;
      },
      deep: true,
      immediate: true,
    },
    frontNDVI: {
      handler(val) {
        this.formItem.frontNDVI = val;
      },
      deep: true,
      immediate: true,
    },
    afterNDVI: {
      handler(val) {
        this.formItem.afterNDVI = val;
      },
      deep: true,
      immediate: true,
    },
    dataPartValue: {
      handler(val) {
        this.merge = val
        console.log(this.merge)
      },
      deep: true,
      immediate: true,
    }
  },
   mounted() {
    this.taskId = this.$route.query.id;
    this.getRegionResultId();
   
  },
  methods: {
    nameShow(){
      let flag = ["YJHLNZWSHJCCP","YJHLDLSHJCCP","YJHLDBSHJCCP","YJHLFWSHJCCP"]
      if (flag.indexOf(this.productionTag) != -1) return "范围文件";
      let tag = ["YJDZNZWSHJCCP","YJDZFWSHJCCP","YJDZDLSHJCCP"]
      if (tag.indexOf(this.productionTag) != -1) return "矢量文件";
      if(this.productionTag == "YJDZZHFWJCCP") return "专题数据";
      return "输入影像";
    },
    isUserCommonImage(){
      let flag = true;
      //应急洪涝灾前范围监测产品YJHLDQFWJCCP,应急火灾火烧迹地变化监测产品YJHSJDBHTQCP
      //应急火灾植被变化监测监测产品YJHZZBBHJCCP,应急洪涝农作物损毁变化监测产品YJHLNZWSHBHJCCP
      let tag = ["YJHLDQFWJCCP", "YJHSJDBHTQCP","YJHZZBBHJCCP","YJHLNZWSHBHJCCP"]
      if (tag.indexOf(this.productionTag) != -1) flag = false;
      return flag;
    },
    isUserFrontNDVI(){
      let flag = false;
      //应急火灾植被变化监测产品YJDZZHFWJCCP,应急洪涝农作物损毁变化监测产品YJHLNZWSHBHJCCP
      let tag = ["YJHZZBBHJCCP", "YJHLNZWSHBHJCCP"]
      if (tag.indexOf(this.productionTag) != -1) flag = true;
      return flag;
    },
    isUserAfterNDVI(){
      let flag = false;
      //应急火灾植被变化监测产品YJDZZHFWJCCP,应急洪涝农作物损毁变化监测产品YJHLNZWSHBHJCCP
      let tag = ["YJHZZBBHJCCP", "YJHLNZWSHBHJCCP"]
      if (tag.indexOf(this.productionTag) != -1) flag = true;
      return flag;
    },
    //参数设置界面可以显示区域选择组件
    isUserRegion() {
      let result = false;
      // 应急洪涝范围监测产品 YJHLFWJCCP,应急火灾林草损毁监测产品YJHZLCSHICCP
      //应急洪涝灾前水体范围监测产品YJHLZQSTFWJCCP,应急洪涝灾前水体范围监测产品YJHLZQSTFWJCCP
      //应急洪涝堤坝损毁监测产品YJHLDBSHJCCP , 应急洪涝农作物损毁变化监测产品YJHLNZWSHBHJCCP
      //应急地质灾害范围监测产品YJDZZHFWJCCP, 应急地质救援监测监测产品YJJYJCCP,
      //应急生产安全事故范围监测产品YJSCAQSGFWJCCP,应急火灾植被变化监测YJHZZBBHJCCP
      let tag = ["YJHLFWJCCP", "YJHZLCSHJCCP","YJHLZQSTFWJCCP","YJHLDQFWJCCP","YJHLDBSHJCCP","YJHLNZWSHBHJCCP","YJDZZHFWJCCP","YJJYJCCP","YJSCAQSGFWJCCP","YJHZZBBHJCCP"];
      if (tag.indexOf(this.productionTag) != -1) result = true;
      return result;
    },
    //输入影像文件路径是共享路径
    isInputIamgePath() {
      let result = false;
      let tag = ["ZSCP"];
      if (tag.indexOf(this.productionTag) != -1) result = true;
      return result;
    },
    //
    isUserDate(){
      let flag = false;
      //应急地质灾害范围监测产品YJDZZHFWJCCP,应急洪涝堤坝损毁监测产品YJHLDBSHJCCP 
      //应急地质救援监测监测产品YJJYJCCP,应急生产安全事故范围监测产品YJSCAQSGFWJCCP
      let tag = ["YJDZZHFWJCCP", "YJHLDBSHJCCP","YJJYJCCP","YJSCAQSGFWJCCP"]
      if (tag.indexOf(this.productionTag) != -1) flag = true;
      return flag;
    },
    //获取区域结果ID
    getRegionResultId() {
      this.regionResultIDListX = [];
      //设置查询区域
      let path = this.$api.emergencyMonitorApi.queryAssociateAreaBytaskId;
      let param = {
        taskId: this.taskId,
      };
      this.http.get(path, param).then((res) => {
        if (res.data.code == 200) {
          let regionResultList = res.data.data;
          this.taskAreaList = regionResultList;
          for (let i = 0; i < regionResultList.length; i++) {
            let region = regionResultList[i];
            // 保存ID
            let tempData1 = {
              regionName: region.regionName,
              regionID: region.id,
              regionCode: region.regionCode,
              regionWkt: region.regionWkt,
              regionType: region.regionType,
            };
            this.regionResultIDListX.push(tempData1);
          }
        }
      });
    },
    regionSelectedChange(value) {
      console.log(value);
      let obj = this.regionResultIDListX.filter((ele) => {
        return ele.regionID == value;
      });
      console.log(obj);
      let item = obj[0];
      let area = {};
      this.formItem.areas = [];
      if(item.regionType == 0) {
        let regionCode = item.regionCode.toString();
        if (regionCode.length == 2){
          this.regionCode = regionCode + "0000";
        } else if (regionCode.length == 4) {
          this.regionCode = regionCode + "00";
        } else {
          this.regionCode = regionCode;
        }
        area.geoName = item.regionName;
        area.geoType = "region";
        area.geoValue = this.regionCode
      }else {
        this.regionCode = item.regionCode;
        area.geoName = item.regionName;
        area.geoType = "polygon";
        area.geoValue = item.regionWkt
      }
      this.formItem.areas.push(area);
      console.log(this.formItem.areas);
      // let obj = this.regionResultIDListX.filter((ele) => {
      //   return ele.regionID == value;
      // });
      // let item = obj[0];
      // let area = {};
      // this.formItem.areas = [];
      // area.geoName = item.regionName;
      // area.geoType = item.regionType == 1 ? "polygon" : "region"; //目前两种 0是region 1是polygon（自定义区域） ；注意  后续可能会加shp
      // area.geoValue = item.regionCode; //默认是region
      // if (item.regionType == 1) {
      //   area.geoValue = item.regionWkt;
      // }
      // this.formItem.areas.push(area);
    },
    //shp文件选择
    selectServerShpFile() {
      let _this = this;
      this.isSelectShp = true;
      this.fileCatalogModal = true; // 打开弹框
      this.$nextTick(() => {
        _this.$refs.refFileCatalogModal.initFileTree(
          {
            type: { name: "file" },
            constraint: { extensions: "*.shp" },
          },
          false
        );
      });
    },
    //输入影像选择
    selectServerFile() {
      let _this = this;
      this.fileCatalogModal = true; // 打开弹框
      this.$nextTick(() => {
        _this.$refs.refFileCatalogModal.initFileTree(
          {
            type: { name: "file" },
            constraint: { extensions: "*.zip,*.tar.gz" },
          },
          false
        );
      });
    },
    treeDataFile(val) {
      this.$emit("treeFile", val);
    },
    fileCatalogModalOk(path) {
      let temp = path.split("#TASK#");
      //   if (temp.length > 3)
      //     this.$Message.info("当前选择大于3个文件,系统会自动处理前三个文件");
      //   let selectFilePath = path.split("#TASK#").slice(0, 1);
      this.fileCatalogModal = false;
      if (this.isSelectShp) this.formItem.shpFile = temp[0];
      else this.formItem.imgDir = temp;
      this.isSelectShp = false;
    },
    fileCatalogModalClose() {
      this.fileCatalogModal = false;
    },

    hideForm() {
      // Remove saved info
      this.formItem.taskName = "";
      this.formItem.imgDir = [];
      this.formItem.waterFileFront = "";
      this.formItem.waterFile = "";
      this.formItem.foregroundImage = "";
      this.formItem.backgroundImage = "";
      this.formItem.frontNDVI = "";
      this.formItem.afterNDVI = "";
      this.formItem.shpFile = "";
      this.regionSelected = "";
      this.formItem.dataDate = "";
      this.merge = false;
      this.$emit("hideForm");
    },

    // async formSubmit() {
    //   this.createTask().then(() => {
    //     this.hideForm();
    //   });
    // },

    judgeConditionsBerforeSubmit() {
      if ( 
        this.productionTag === 'YJHLDQFWJCCP' &&
        ( this.formItem.waterFileFront.length < 1 &&
        this.formItem.waterFile.length < 1 )
         ) {
        this.$Message.warning("请先选择数据!!");
        return false;
      }
      if ( 
        this.productionTag === 'YJHSJDBHTQCP' &&
        ( this.formItem.foregroundImage.length < 1 &&
        this.formItem.backgroundImage.length < 1 )
         ) {
        this.$Message.warning("请先选择数据!!");
        return false;
      }
      if((this.isUserFrontNDVI() || this.isUserAfterNDVI()) &&
         ( this.formItem.frontNDVI.length < 1 
         && this.formItem.afterNDVI.length < 1)
         ){
        this.$Message.warning("请先选择数据!!");
        return false;
      }
      if (this.isUserCommonImage() && this.formItem.imgDir.length < 1) {
        this.$Message.warning("请先选择数据!!");
        return false;
      }
      if (this.flowList.length == 0) {
        this.$Message.warning("无可用流程!!");
        return false;
      }
      if (this.isUserDate() && !this.formItem.dataDate) {
        this.$Message.warning("请输入日期!!");
        return false;
      }
      if (
        this.productionTag === "YJCJCP" &&
        this.radioGroupRengion === "region" &&
        this.formItem.areas.length < 1
      ) {
        this.$Message.warning("请先选择区域范围!!");
        this.formItem.shpFile = "";
        return false;
      }
      if (
        this.productionTag === "YJCJCP" &&
        this.radioGroupRengion === "shpFile" &&
        !this.formItem.shpFile
      ) {
        this.$Message.warning("请先选择矢量文件!!");
        this.formItem.areas = [];
        return false;
      }
      if (this.isUserRegion() && this.formItem.areas.length < 1) {
        this.$Message.warning("请先选择区域范围!!");
        this.formItem.shpFile = "";
        return false;
      }
      return true;
    },

    formSubmit() {
      let _this = this;
      let path = this.$api.queryDealApi.disasterDataWorkFlowProduct;
      if (!this.judgeConditionsBerforeSubmit()) return;
      let flow = this.flowList.filter(
        (f) => f.flowName === this.formItem.taskName
      )[0];
      if (!flow) {
        this.$Message.warning("请先选择流程!!");
        return;
      }
      let user = this.$store.state.user;
      let param = {
        dataDate: this.formItem.dataDate ? this.formItem.dataDate : "",
        dataList: this.formItem.imgDir,
        flowId: flow.flowId,
        userId: user.userId,
        userName: user.userName,
        taskId: this.taskId,
        taskSource: this.taskSource,
        priority: 1,
        regionCode: this.regionCode,
        areas: this.formItem.areas, //areas和 shpFile任意一个都可以
        shpFile: this.formItem.shpFile,
        waterFileFront: this.formItem.waterFileFront[0],
        waterFile: this.formItem.waterFile ? this.formItem.waterFile : [],
        foregroundImage: this.formItem.foregroundImage[0],
        backgroundImage: this.formItem.backgroundImage[0],
        ndvifile: this.formItem.frontNDVI[0],
        ndvifileBack: this.formItem.afterNDVI[0],
        merge: !this.merge,
      };
      console.log(param);
      this.http.post(path, param).then((res) => {
        this.hideForm();
        if (res.data.success) {
          this.$Message.success("开始执行.....");
        } else {
          this.$Message.error("执行失败！");
        }
      });
    },

    formCancel() {
      this.hideForm();
    },

    async changeTask(p) {
      this.taskSource = p.classify;
      this.productionName = p.productionName;

      this.productionTag = p.productionTag;
      console.log(this.productionTag)

      const path = this.$api.queryDealApi.query;
      const param = {
        params: {
          satellite: p.satellite,
          sensor: p.sensor,
          taskType: p.productionTag,
        },
      };

      const { data } = await Axios.get(path, param);
      if (!data || !data.success)
        this.$Message.warning("通过产品信息获取流程列表失败");
      else this.flowList = data.data.dataList;
    },
  },
};
</script>

<style lang="scss">
#produceTaskWrapper .ivu-drawer {
  width: 100% !important;
  height: 100% !important;

  z-index: 3;
}

#produceTaskWrapper .ivu-drawer-body {
  display: flex;
  align-items: center;
  justify-content: center;
}

#produceTaskWrapper .ivu-drawer-content {
  background-color: rgba(0, 0, 0, 0.2);
}

#produceTaskWrapper .produceTask {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 60px;
  border-radius: 8px;
  height: auto;
  width: auto;
  background-color: white;
}

#produceTaskWrapper .ivu-form {
  width: 600px;
}
#produceTaskWrapper .ivu-form-item {
  width: 100%;
}

#produceTaskWrapper .ivu-form-item label {
  width: unset;
}

#produceTaskWrapper .ivu-form-item-content {
  text-align: center;
}

// remove left margin of buttons
#produceTaskWrapper .formBtnGroup .ivu-form-item-content {
  margin-left: 0 !important;
}

#produceTaskWrapper .ivu-btn {
  margin-left: 10px;
  margin-right: 10px;
}

#produceTaskWrapper .formTitle {
  align-self: start !important;
  margin-bottom: 32px;
  font-weight: bold;
  font-size: 16px;
}

#produceTaskWrapper .ivu-input[disabled],
fieldset[disabled] .ivu-input {
  // min-width: 400px;
  margin-bottom: 4px;
  background-color: rgba(0, 0, 0, 0.05);
  color: black;
}
.radioGroup {
  width: 526px;
  margin-top: -6px;
  margin-left: -28px;
}
.ivu-radio {
  margin-top: 10px;
}
.rightBtn {
  width: 45px;
  height: 34px;
  margin-left: 10px;
  margin-top: -2px;
}
</style>